// pages/cart/cart.js
import {
    checklogin
} from '../../utils/login.js';
import {
    axios
} from '../../utils/ajax.js';
import {
    region
} from '../../data/region.js';
let app = getApp()

Page({
    data: {
        empty: false,
        defaultAddr: [],
        cartData: {},
        cartGoods: {},
        activityData: {
            activityId: '',
            activityCheck: ''
        },
        mask: false,
        showpreferentialway: false,
        couponboxshow: false,
        userCntl: 0,
        //未支付订单数
        unpaidOrderNum: '',
        nodes: '',
        //订单类型   0 线上订单   1 线下提货订单
        ordertype: 0,
        isShow: true,
        //订单类型弹窗状态
        ordertypeshow: false,
        iPhoneX: false,
        isOpenVip: null
    },

    onShow: function() {
        this.setData({
            isShow: true
        })

        if (app.globalData.model.substr(0, 8) == 'iPhone X') {
            this.setData({
                iPhoneX: true
            })
        }

        checklogin().then((res) => {
            this.getAddress()
            this.getInvoice()
            this.getRemark()
        })
    },

    onHide: function() {
        this.setData({
            isShow: false
        })
    },

    onUnload: function() {
        this.setData({
            isShow: false
        })
    },

    onLoad: function(options) {
        console.log('isGroup:' + options.isGroup + ', buytype:' + options.buytype + ', fightId:' + options.fightId)
        this.setData({
            isGroup: options.isGroup, // 0：普通购买 1：拼团购买
            buytype: options.buytype, // 0：直接购买 1：vip购买
            fightId: options.fightId ? options.fightId : 0
        })
        if (this.data.isGroup == 0) {
            this.setData({
                isOpenVip: this.data.buytype == 1 ? 1 : 0
            })
        }
        checklogin().then((res) => {
            this.setData({
                unpaidOrderNum: wx.getStorageSync('unpaidOrderNum') ? wx.getStorageSync('unpaidOrderNum') : 0
            })
            this.getRollMsg()
        })
    },

    getCartData: function() {
        wx.getStorage({
            key: "cartGoods",
            success: res => {
                console.log('storage-cartGoods:', res.data)
                this.setData({
                    cartGoods: res.data
                })
                this.setData({
                    empty: false
                })
                axios({
                    url: '/cart/cartItem',
                    data: {
                        ...this.data.cartGoods,
                        ...this.data.activityData,
                        ...getUser(),
                        userCntl: this.data.activityData.activityId == '' ? 0 : 1,
                        isGroup: this.data.isGroup,
                        isOpenVip: this.data.isOpenVip,
                        addressId: this.data.defaultAddr ? this.data.defaultAddr.addressId : ''
                    }
                }).then(res => {
                    console.log('购物车接口：', res.data)
                    this.setData({
                        cartData: res.data,
                        unpaidOrderNum: res.data.unpaidOrderNum ? res.data.unpaidOrderNum : 0
                    })
                    //把待支付订单写入缓存
                    wx.setStorageSync('unpaidOrderNum', res.data.unpaidOrderNum)
                    this.setCartStorage({})
                    // console.log('活动信息：', this.data.activityData)
                })
            },
            fail: () => {
                this.setData({
                    empty: true
                })
            }
        })
    },

    setCartStorage: function(json) {
        let cartGoods, specId = [],
            goodsId = [],
            num = [],
            goodsCheck = [];
        this.data.cartData.specials.map(special => {
            special.goods.map(goods => {
                specId.push(goods.specId);
                goodsId.push(goods.goodsId);
                num.push(goods.goodsNum);
                goodsCheck.push(goods.goodsCheck);
            })
        })
        cartGoods = {
            specId: specId.join(','),
            goodsId: goodsId.join(','),
            num: num.join(','),
            goodsCheck: goodsCheck.join(',')
        }
        // console.log(cartGoods)
        if (!cartGoods.goodsId) {
            this.setData({
                cartData: {}
            });
            wx.removeStorageSync("cartGoods");
            wx.removeStorageSync("invoice");
            wx.removeStorageSync("remark");
            wx.removeTabBarBadge({
                index: 1
            });
            if (json.pay) {
                json.refresh ? this.getCartData() : null;
                return;
            }
            wx.switchTab({
                url: '/pages/home/home'
            })
            return;
        } else {
            wx.setStorageSync("cartGoods", cartGoods);
            // wx.setTabBarBadge({
            //     index: 1,
            //     text: String(goodsId.length)
            // });
        }
        json.refresh && this.getCartData();
    },

    checkGoods: function(e) {
        let {
            sIndex,
            gIndex,
            goodsCheck
        } = e.currentTarget.dataset;
        let cartData = this.data.cartData;
        cartData.specials[sIndex].goods[gIndex].goodsCheck = parseInt(goodsCheck) ? 0 : 1;
        this.setData({
            cartData: cartData
        });
        console.log(cartData)
        this.setCartStorage({
            refresh: true
        });
    },

    minusGoods: function(e) {
        let {
            sIndex,
            gIndex
        } = e.currentTarget.dataset;
        let cartData = this.data.cartData,
            goodsNum = cartData.specials[sIndex].goods[gIndex].goodsNum;
        if (goodsNum > 1) {
            cartData.specials[sIndex].goods[gIndex].goodsNum = goodsNum - 1;
            this.setData({
                cartData: cartData
            });
            this.setCartStorage({
                refresh: true
            });
        }
    },

    plusGoods: function(e) {
        let {
            sIndex,
            gIndex
        } = e.currentTarget.dataset;
        let cartData = this.data.cartData,
            goodsNum = cartData.specials[sIndex].goods[gIndex].goodsNum,
            stocknum = cartData.specials[sIndex].goods[gIndex].stocknum;
        if (goodsNum < stocknum) {
            cartData.specials[sIndex].goods[gIndex].goodsNum = goodsNum + 1;
            this.setData({
                cartData: cartData
            });
            this.setCartStorage({
                refresh: true
            });
        }
    },

    deleteGoods: function(e) {
        let {
            sIndex,
            gIndex
        } = e.currentTarget.dataset;
        let cartData = this.data.cartData;
        wx.showModal({
            title: '提示',
            content: '确认将该商品从购物车中移除吗',
            cancelText: '否',
            confirmText: '是',
            confirmColor: '#02BB00',
            success: res => {
                if (res.confirm) {
                    cartData.specials[sIndex].goods.splice(gIndex, 1);
                    cartData.specials[sIndex].goods.length == 0 && cartData.specials.splice(sIndex, 1);
                    this.setData({
                        cartData: cartData
                    });
                    this.setCartStorage({
                        refresh: true
                    });
                }
            }
        })
    },

    getAddress: function() {
        axios({
            url: '/address/addressList',
            data: getUser()
        }).then((res) => {
            console.log('地址信息：', res.data)
            let defaultAddr = res.data.addressInfo ? res.data.addressInfo.find(item => item.isDefault == 1) : {};
            this.setData({
                defaultAddr: getAddressName(defaultAddr)
            })
            console.log('默认地址：', this.data.defaultAddr)
            this.getCartData()
        })
    },

    getInvoice: function() {
        this.setData({
            invoice: wx.getStorageSync("invoice") || {}
        })
    },

    getRemark: function() {
        this.setData({
            remark: wx.getStorageSync("remark") || ''
        })
    },

    getRollMsg: function() {
        axios({
            url: '/home/groupAdvertisement'
        }).then(res => {
            this.setData({
                rollMsg: res.data.grouplist,
                news: res.data.grouplist[0]
            })
        })

    },

    checkVip: function() {
        this.setData({
            isOpenVip: this.data.isOpenVip ? 0 : 1
        }, () => {
            this.getCartData()
        })
    },

    // 选择优惠方式
    chooseWay: function(e) {
        let {
            activityId: thisActivityId,
            index
        } = e.currentTarget.dataset;
        console.log(thisActivityId, index)
        let activityData = this.data.activityData;
        let chooseOptions = this.data.chooseData.data;
        if (activityData.activityId) {
            let activityId = activityData.activityId.split(',');
            let activityCheck = activityData.activityCheck.split(',');
            let allOptions = [];
            this.data.cartData.activitys.map(item => {
                item.options.map(it => {
                    allOptions.push(it.couponId)
                })
            })
            for (var i = 0; i < chooseOptions.length; i++) {
                activityId.map((value, idx) => {
                    if (value == chooseOptions[i].couponId || allOptions.indexOf(value) < 0) {
                        activityId.splice(idx, 1);
                        activityCheck.pop();
                    }
                })
            }
            activityId.push(chooseOptions[index].couponId);
            activityCheck.push('1');
            activityData.activityId = activityId.join(',');
            activityData.activityCheck = activityCheck.join(',');
        } else {
            activityData.activityId = chooseOptions[index].couponId;
            activityData.activityCheck = '1';
        }
        this.setData({
            activityData: activityData
        })
        this.hidePopup();
        this.getCartData();
    },

    // 领取优惠券
    getCoupon: function(e) {
        axios({
            url: '/coupon/get',
            data: {
                couponId: e.currentTarget.dataset.couponId,
                ...getUser()
            }
        }).then(res => {
            this.hidePopup();
            this.getCartData();
        })
    },

    // 打开优惠方式
    showChoose(e) {
        let {
            type,
            aIndex = '',
            sIndex = ''
        } = e.currentTarget.dataset;
        console.log(type, aIndex, sIndex)
        let options = [];
        if (type == 'discountWay') {
            let activityId = this.data.cartData.activitys[aIndex].activityId;
            console.log(activityId)
            options = this.data.cartData.activitys[aIndex].options.map(item => {
                item.choose = item.couponId == activityId ? true : false;
                return item;
            });
        }
        this.setData({
            showpreferentialway: true,
            mask: true,
            chooseData: {
                type: type,
                data: type == "specialCoupon" ? this.data.cartData.specials[sIndex].events.find(item => item.coupons.length > 0).coupons : options
            }
        })
    },

    // 领券
    showGetCoupon(e) {
        let sIndex = e.currentTarget.dataset.sIndex;
        this.setData({
            couponboxshow: true,
            mask: true,
            getCouponData: this.data.cartData.specials[sIndex].events.find(item => item.options.length > 0).options
        })
    },

    // 关闭弹窗
    hidePopup() {
        this.setData({
            showpreferentialway: false,
            couponboxshow: false,
            mask: false,
            ordertypeshow: false
        })
    },

    // 提交订单
    commitorder() {
        let data = {
            addressId: this.data.defaultAddr ? this.data.defaultAddr.addressId : '',
            ...this.data.cartGoods,
            ...this.data.activityData,
            ...getUser(),
            isGroup: this.data.isGroup,
            isOpenVip: this.data.isOpenVip,
            fightId: this.data.fightId
        }
        if (this.data.invoice.needInvoice) {
            data.isInvoice = this.data.invoice.needInvoice;
            data.invoiceTitle = this.data.invoice.invoiceInfo.invoiceTitle;
            this.data.invoice.invoiceInfo.invoiceCode ? data.invoiceCode = this.data.invoice.invoiceInfo.invoiceCode : null;
        }
        if (this.data.remark) {
            data.remark = this.data.remark;
        }
        let self = this;
        console.log('创建订单入参：', data)
        // 创建订单
        axios({
            url: '/order/create',
            data: data
        }).then(res => {
            let orderNo = res.data.orderNo;
            // 微信支付
            axios({
                url: '/pay/wxpay',
                data: {
                    orderNo: orderNo,
                    ...getUser()
                }
            }).then(res => {
                wx.requestPayment({
                    timeStamp: res.data.timeStamp,
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    signType: res.data.signType,
                    paySign: res.data.paySign,
                    success: () => {
                        wx.showToast({
                            title: '支付成功',
                            icon: "success",
                            duration: 1500
                        });
                        // 统计
                        // let itemInfo = [];
                        // self.data.cartData.specials.map(item => {
                        //     item.goods.map(it => {
                        //         it.goodsCheck == 1 && itemInfo.push(it);
                        //     })
                        // })
                        // sdk.iap.currencyPurchase({
                        //     orderId: orderNo,
                        //     amount: self.data.cartData.totalPrice,
                        //     currencyType: 'CNY',
                        //     payType: 'wx',
                        //     itemId: itemInfo,
                        //     itemCount: self.data.cartData.num
                        // });
                        self.cleanBuyGoods()
                        setTimeout(() => {
                            wx.redirectTo({
                                url: '/pages/cart/dealresult/dealresult?orderNo=' + orderNo
                            })
                        }, 1500)
                    },
                    fail: () => {
                        if (this.data.isOpenVip != 1) {
                            self.cleanBuyGoods()
                            wx.showToast({
                                title: '支付失败',
                                icon: "none",
                                duration: 1500,
                                success: function() {
                                    wx.navigateTo({
                                        url: '/pages/my/orderlist/orderlist?type=2'
                                    })
                                }
                            })
                            let unpaidOrderNum = this.data.unpaidOrderNum;
                            unpaidOrderNum++;
                            this.setData({
                                unpaidOrderNum: unpaidOrderNum
                            })
                            wx.setStorageSync('unpaidOrderNum', unpaidOrderNum)
                        }
                    },
                })
            }).catch(res => {
                self.cleanBuyGoods()
            })
        })
    },

    // 清空已购买商品
    cleanBuyGoods: function() {
        wx.removeStorageSync("invoice");
        wx.removeStorageSync("remark");
        let cartData = this.data.cartData;
        for (let i = cartData.specials.length - 1; i >= 0; i--) {
            for (let j = cartData.specials[i].goods.length - 1; j >= 0; j--) {
                cartData.specials[i].goods[j].goodsCheck == 1 && cartData.specials[i].goods.splice(j, 1);
            }
            cartData.specials[i].goods.length == 0 && cartData.specials.splice(i, 1);
        }
        this.setData({
            cartData: cartData,
            activityData: {
                activityId: '',
                activityCheck: ''
            },
            userCntl: 0
        })
        this.setCartStorage({
            refresh: true,
            pay: true
        });
    },

    //选择订单类型
    chooseordertype(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            ordertype: index
        })
        //点击线下提货订单
        if (index == 1) {
            wx.showModal({
                content: '线下提货订单仅针对有淘集集推荐人的用户，请确认有闪电推荐人为您提供提货服务。',
                success: function(res) {
                    if (res.confirm) {
                        console.log('用户点击确定')
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        }
    },

    //选择订单类型
    choosetype() {
        this.setData({
            mask: true,
            ordertypeshow: true
        })
    }
})

function getUser() {
    let {
        userid = '', token = ''
    } = wx.getStorageSync('userinfo')
    return {
        userid,
        token
    }
}

function getAddressName(defaultAddr) {
    if (defaultAddr.provinceId) {
        defaultAddr.province = region.find(item => item.id == defaultAddr.provinceId).name;
        defaultAddr.city = region.find(item => item.id == defaultAddr.provinceId).childs.find(item => item.id == defaultAddr.cityId).name;
        defaultAddr.district = region.find(item => item.id == defaultAddr.provinceId).childs.find(item => item.id == defaultAddr.cityId).childs.find(item => item.id == defaultAddr.districtId).name;
        return defaultAddr
    }
}